

bt.module({builder: function(bt) {
    var j$ = jQuery;
    var currentMarker;
    var map;
    var latlngbounds;
    var info_windows = {};
    var markers = {}
    var index = -1;
    var points;
    var geocoder;

    var totalPhotos = 0;
    var currentPhoto = 0;
    var DISPLAY_PHOTOS = 4;
    var PHOTO_WIDTH = 193;

    var _scrollTo = function(offset) {
        offset = Math.max(0, Math.min(totalPhotos - DISPLAY_PHOTOS, offset));
        if(offset != currentPhoto) {
            currentPhoto = offset;
            j$(".photo-list .photos-inner").animate({left: "-" + (PHOTO_WIDTH * currentPhoto)}, "slow")
        }
    };

    var popup = function(new_index) {
        if (index >= 0)
            info_windows[index].close();
        else if (map.getZoom() < 14)
            map.setZoom(14);
        info_windows[new_index].open(map, markers[new_index]);
        index = new_index;
    }

    var addWaypoint = function(i, data, type) {
        var image;
        var contentString = '';
        var prefix = '<div id="map_popup">';
        var postfix = '<p><a class="right-here" href="javascript:;">就在这里</a></p></div>';
        if (type == "start") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_start.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<p class="start">游记起点</p>' + postfix;
        } else if (type == "photo") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_photo.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<a href="#wp' + data[2] + '"><img width="180" height="135" src="' + data[1] + '" /></a>' + postfix;
        } else if (type == "text") {
            image = new google.maps.MarkerImage(STATIC_URL+'img/icon_new_text.png',
                new google.maps.Size(35, 37),
                new google.maps.Point(0, 0),
                new google.maps.Point(15, 34));
            contentString = prefix + '<a class="text" href="#wp' + data[2] + '">"' + data[1] + '"</a>' + postfix;
        }

        var marker = new google.maps.Marker({
            position: data[0],
            map: map,
            icon: image
        });

        markers[i] = marker;
        var infowindow = new google.maps.InfoWindow({
            content: contentString
        });

        google.maps.event.addListener(infowindow, 'domready', function() {
            j$(".right-here").click(function() {
                var pos = markers[i].getPosition();
                placeMarker(map, pos.lat(), pos.lng());
            });
        });

        info_windows[i] = infowindow;

        google.maps.event.addListener(marker, 'click', function() {
            popup(i);
        });
    }

    function updateMarkerLocation() {
        var latlng = currentMarker.getPosition();
        $('#latitude').val(latlng.lat());
        $('#longitude').val(latlng.lng());
    }

    function getData(point) {
        var items = point.children();
        var lat = parseFloat($(items[0]).text());
        var lon = parseFloat($(items[1]).text());
        var content = $(items[2]).text();
        var wp_id = null;
        if (items.length > 3)
            wp_id = $(items[3]).text();
        return [new google.maps.LatLng(lat, lon), content, wp_id];
    }

    function placeMarker(map, lat, lng) {
        if (currentMarker) {
            currentMarker.setMap(null);
        }

        currentMarker= new google.maps.Marker({
            draggable: true,
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(lat, lng), 
            map: map
        });

        updateMarkerLocation();
        google.maps.event.addListener(currentMarker, 'dragend', updateMarkerLocation);
    }

    var _clearEditForm = function() {
        if(currentMarker) {
            currentMarker.setMap(null);
        }
        $('#edit-form #latitude').val("");
        $('#edit-form #longitude').val("");
        $('#edit-form #city').val("");
        $('#edit-form #province').val("");
        $('#edit-form #country').val("");
        $("#edit-form #text").text("");
        $("#edit-form .date").val("");
        $("#edit-form .hour").val("");
        $("#edit-form .minute").val("");
    };

    var _alertUnsavedChange = function() {
        var changed = false;
        var obj = j$(".selected");
        var old_lat = parseFloat(obj.find(".hidden-lat").val());
        var old_lng = parseFloat(obj.find(".hidden-lon").val());
        var new_lat = parseFloat($('#latitude').val());
        var new_lng = parseFloat($('#longitude').val());
        if( (!old_lat && new_lat) ||
            (!old_lng && new_lng) ||
            Math.abs(old_lat - new_lat) > 1e-8 ||
            Math.abs(old_lng - new_lng) > 1e-8 ||
            obj.find(".hidden-text").text() != $("#edit-form #text").val() ||
            obj.find(".date").val() != $("#edit-form .date").val() ||
            parseInt(obj.find(".hour").val()) != parseInt($("#edit-form .hour").val()) ||
            parseInt(obj.find(".minute").val()) != parseInt($("#edit-form .minute").val())) {
            return "您尚有未保存的改动，确定离开？";
        }
    };

    var edit = function(obj) {
        _clearEditForm();
        if (index >= 0) {
            info_windows[index].close();
        }
        $('.save-button .result').hide();
        $(".photos .selected").removeClass("selected");
        if(!obj) {
            obj = $(".photos .photo-item").first();
        } else {
            obj = $(obj);
        }
        obj.addClass("selected");

        var lat = obj.find(".hidden-lat").val();
        var lng = obj.find(".hidden-lon").val();
        if (lat && lng) {
            lat = parseFloat(lat);
            lng = parseFloat(lng);
            placeMarker(map, lat, lng);
            updateMarkerLocation();
            map.setCenter(new google.maps.LatLng(lat, lng));
            map.setZoom(14);
        } else {
            /*
            if (points.length == 1)
                map.setCenter(coordinates[0]);
            else {
                map.fitBounds(latlngbounds);
            }
            */
        }

        $("#edit-form #text").val(obj.find(".hidden-text").text());
        $("#edit-form .date").val(obj.find(".date").val());
        $("#edit-form .hour").val(obj.find(".hour").val());
        $("#edit-form .minute").val(obj.find(".minute").val());
        $("#edit-form #privacy").val(obj.find(".hidden-privacy").val());
        $("#edit-form .date").change();
    };

    var editNext = function() {
        var next = j$(".photos .selected").next();
        if(next.length > 0) {
            edit(next);
        }
        _scrollTo(j$(".photo-item").index(j$(".selected")));
    };

    var initDatepicker = function() {
        $.datepicker.regional['zh-CN'] = {
            closeText: '关闭',
            prevText: '&#x3c;上月',
            nextText: '下月&#x3e;',
            currentText: '今天',
            monthNames: ['一月','二月','三月','四月','五月','六月',
            '七月','八月','九月','十月','十一月','十二月'],
            monthNamesShort: ['一','二','三','四','五','六',
            '七','八','九','十','十一','十二'],
            dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
            dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'],
            dayNamesMin: ['日','一','二','三','四','五','六'],
            weekHeader: '周',
            dateFormat: 'yy-mm-dd',
            firstDay: 1,
            isRTL: false,
            showMonthAfterYear: true,
            yearSuffix: '年'};
        $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
        $("input.date").datepicker({
            yearRange: "-20:+0",
            changeYear: true
        });
    };

    var searchAddress = function(address, callback) {
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                if (map.getZoom() < 14)
                    map.setZoom(14);
            } else {
                alert("未找到相关位置，修改搜索条件再试试？");
            }
        });
    };

    var _submit = function() {
        var wp = $(".photos .selected");
        var trip_id = $("#edit-form").attr("data-trip-id");
        var wp_id = wp.attr("data-id");
        var args = $("#edit-form").serialize();
        var url = "/trips/v1_1/" + trip_id + "/waypoints/" + wp_id + "/edit/";
        $.ajax({
            type: "POST",
            url: url,
            data: args
        }).done(function(msg) {
            if(msg.error) {
                alert(msg.error);
            } else {
                j$('.selected .hidden-lat').val(j$('#latitude').val());
                j$('.selected .hidden-lon').val(j$('#longitude').val());
                j$('.selected .hidden-text').text(j$('#text').val());
                j$('.selected .date').val(j$("#edit-form .date").val());
                j$('.selected .hour').val(j$("#edit-form .hour").val());
                j$('.selected .minute').val(j$("#edit-form .minute").val());
                j$('.save-button .result').fadeIn(function() {
                    editNext();
                });
            }
            j$("#save-edit").css('opacity', 1);
        });
    };

    var _done = function() {
        $.ajax({
            type: "POST",
            data: bt.misc.initPostData(),
            success: function(resp) {
                if(resp.error) {
                    alert(resp.error);
                } else {
                    if(resp.wp_ids.length > 0) {
                        edit(j$("#wp" + resp.wp_ids[0]));
                        _scrollTo(j$(".photo-item").index(j$(".selected")));
                        j$("#no-date-wp-tip").fadeIn();
                    } else {
                        j$(location).attr("href", j$(".done").attr("href"));
                    }
                }
            }
        });
    };

    var initialize = function() {
        var options = {
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map"), options);

        points = $('#map_data').children();
        var coordinates = [];
        latlngbounds = new google.maps.LatLngBounds();
        points.each(function(i, point) {
            point = $(point);
            var type = point.attr('class');
            data = getData(point);
            if (type != 'track')
                addWaypoint(i, data, type);
            coordinates.push(data[0]);
            if(coordinates[0].lat() && coordinates[0].lng()) {
                latlngbounds.extend(data[0]);
            }
        });

        var path = new google.maps.Polyline({
            path: coordinates,
            strokeColor: "#0695f8",
            strokeOpacity: 1.0,
            strokeWeight: 4
        });
        path.setMap(map);

        geocoder = new google.maps.Geocoder();
        google.maps.event.addListener(path, 'click', function(event) {
            placeMarker(map, event.latLng.lat(), event.latLng.lng());
        });

        google.maps.event.addListener(map, 'click', function(event) {
            placeMarker(map, event.latLng.lat(), event.latLng.lng());
        });

        edit();

        if(!map.getCenter()) {
            if (points.length == 1) {
                if(coordinates[0].lat() && coordinates[0].lng()) {
                    map.setCenter(coordinates[0]);
                } else {
                    latlngbounds.extend(new google.maps.LatLng(70, -180));
                    latlngbounds.extend(new google.maps.LatLng(-30, 180));
                    map.fitBounds(latlngbounds);
                }
            } else {
                map.fitBounds(latlngbounds);
            }
        }
    };

    j$(function() {
        j$('img.photo').bind('load', function(){
            bt.misc.centerAlignImg(j$(this), 120, 171);
        });
    });

    j$(document).ready(function() {
        initDatepicker();

        if ($.browser.msie) {
            var maxWidth = 240;
            var photos = $('img.photo');
            for (var i = 0; i < photos.length; i++)
                if ($(photos[i]).width() > maxWidth)
                    $(photos[i]).width(maxWidth);
        }

        j$(".photo-item").click(function(e) {
            var msg = _alertUnsavedChange();
            if(j$(this).hasClass("selected")) {
                return;
            }
            if(msg) {
                rtn = confirm(msg);
                if(rtn) {
                    edit(j$(this));
                }
            } else {
                edit(j$(this));
            }
            e.preventDefault();
            e.stopPropagation();
        });

        totalPhotos = j$(".photos-inner .photo-item").length;

        j$(".pos-search .search-btn").click(function() {
            $('.pos-search input').blur();
            var address = $('.pos-search input').val();
            searchAddress(address);
            return false;
        });

        $('.pos-search input').keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                $('.pos-search input').blur();
                var address = $('.pos-search input').val();
                searchAddress(address);
                e.preventDefault();
            }
        });

        j$(".left-arrow").click(function() {
            _scrollTo(currentPhoto - 1);
        });

        j$(".right-arrow").click(function() {
            _scrollTo(currentPhoto + 1);
        });

        j$(window).on('beforeunload', function() {
            return _alertUnsavedChange();
        });

        j$("#save-edit").click(function() {
            j$("#save-edit").css('opacity', 0.3);
            var lat = $('#latitude').val();
            var lng = $('#longitude').val();
            if (lat && lng) {
                var latlng = new google.maps.LatLng(lat, lng);
                geocoder.geocode({'latLng': latlng}, function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results[0] && results[0].address_components) {
                            var country_code, province, city;
                            for (var i in results[0].address_components) {
                                if(!results[0].address_components[i].types) {
                                    continue;
                                }
                                if ($.inArray('country', results[0].address_components[i].types) >= 0) {
                                    country_code = results[0].address_components[i].short_name;
                                } else if ($.inArray('administrative_area_level_1', results[0].address_components[i].types) >= 0) {
                                    province = results[0].address_components[i].long_name;
                                } else if ($.inArray('locality', results[0].address_components[i].types) >= 0) {
                                    city = results[0].address_components[i].long_name;
                                }
                            }
                            if (country_code) $('#country').val(country_code);
                            if (province) $('#province').val(province);
                            if (city) $('#city').val(city);
                        }
                    }
                    _submit();
                });
            } else {
                _submit();
            }
        });


        j$("#edit-form .date").change(function(e) {
            if(j$.trim(j$(this).val()) == "") {
                j$(this).addClass("date-undefined");
                j$("#no-date-wp-tip").fadeIn();
            } else {
                j$(".time .date").removeClass("date-undefined");
                j$("#no-date-wp-tip").fadeOut();
            } 
        });

        j$(".done").click(function() {
            var msg = _alertUnsavedChange();
            if(msg) {
                rtn = confirm(msg);
                if(rtn) {
                    _done();
                }
            } else {
                _done();
            }
            return false;
        });

        j$("img.photo").show().lazyload({
            container: j$(".photos-inner"),
            effect: "fadeIn",
            threshold: 200,
            placeholder: STATIC_URL+"img/ajax_loader_240px.gif"
        });

        j$(document).click(function() {
            j$("#no-date-wp-tip").fadeOut();
        });

    });

    window.onload = function() { initialize(); };
}});
